package dat255.calendarclock.view;

import java.util.GregorianCalendar;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ListView;
import dat255.calendarclock.model.event.DateHelper;
import dat255.calendarclock.model.event.EventHandler;
import dat255.calendarclock.model.event.SubEvent;

/**
 * A list used to display events.
 * 
 * @author Marcus Hultman
 * 
 */
public class ListCalendarView extends ListView {

	// Field

	private LayoutInflater layoutInflater;
	private DateHelper dayComparator = new DateHelper();
	private ListCalendarAdapter listAdapter;
	private boolean showSeparators = true;

	// Constructor

	public ListCalendarView(Context context, AttributeSet attrs) {
		this(context, attrs, GregorianCalendar.YEAR);
	}

	public ListCalendarView(Context context, AttributeSet attrs, int precision) {
		super(context, attrs);
		// Disable scrollbar
		setVerticalScrollBarEnabled(false);
		layoutInflater = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		loadEvents(precision);
	}

	// Public methods

	public boolean getShowSeparators() {
		return this.showSeparators;
	}

	public void setShowSeparators(boolean showSeparators) {
		this.showSeparators = showSeparators;
	}

	/**
	 * Loads the list with the specified precision with the selected day as
	 * origin
	 * 
	 * @param precision
	 */
	public void loadEvents(int precision) {
		// Get our eventhandler
		EventHandler eventHandler = EventHandler.getInstance();
		// Adds all events
		List<SubEvent> events = eventHandler.getEvents(
				eventHandler.getSelectedDay(), precision);
		// A listadapter that holds the events and present them in a propriate
		// way
		listAdapter = new ListCalendarAdapter(layoutInflater);
		if (!events.isEmpty()) {
			GregorianCalendar currentDate = null;
			for (SubEvent event : events) {
				GregorianCalendar date = event.getDate();
				if (showSeparators
						&& dayComparator.compare(date, currentDate) != 0) {
					listAdapter
							.addSeparatorItem(currentDate = (GregorianCalendar) date
									.clone());
				}
				listAdapter.addItem(event);
			}
		} else {
			listAdapter.setNoEvents(true);
		}
		// Set adapter
		setAdapter(listAdapter);
	}

	
}
